package com.commerce.service.impl;

import com.commerce.common.Reminder;
import com.commerce.mapping.ADMapping;
import com.commerce.model.AD;
import com.commerce.page.ADPage;
import com.commerce.page.Page;
import com.commerce.service.ADService;
import com.commerce.util.Base64Img;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

@Service
public class ADServiceImpl implements ADService {

    @Autowired
    private ADMapping adMapping;

    @Value("${web.upload-path}")
    private String webuploadpath;

    /**
     * 新增
     *
     * @param ad
     * @return
     */
    @Override
    public String insert(AD ad , HttpServletRequest request) {
        ad.setImgurl(Base64Img.uploadImg(ad.getImgurl(),webuploadpath));
        if(ad.getImgurl() == null){
            return Reminder.uploadimgerror.name();
        }
        return adMapping.insert(ad)>0?Reminder.success.getName():Reminder.saveerror.getName();
    }

    /**
     * 修改
     *
     * @param ad
     * @return
     */
    @Override
    public String update(AD ad , HttpServletRequest request) {
        if(ad.getImgurl() != null && ad.getImgurl().length()>100){
            ad.setImgurl(Base64Img.uploadImg(ad.getImgurl(),webuploadpath));
            if(ad.getImgurl() == null){
                return Reminder.uploadimgerror.name();
            }
        }
        return adMapping.update(ad)>0?Reminder.success.getName():Reminder.updateerror.getName();
    }

    /**
     * 根据ID删除
     * @param id
     * @return
     */
    @Override
    public String deleteById(int id) {
        return adMapping.deleteById(id)>0?Reminder.success.getName():Reminder.deleteerror.getName();
    }

    /**
     * 根据ID查询
     *
     * @param id
     * @return
     */
    @Override
    public AD selectById(int id) {
        return adMapping.selectById(id);
    }

    /**
     * 分辨查询
     *
     * @param adPage
     * @return
     */
    @Override
    public Page selectByPage(ADPage adPage) {
        PageHelper.startPage(adPage.getPage() , adPage.getLimit());
        adPage.setList(adMapping.selectPage(adPage));
        return adPage;
    }

    /**
     * 开启或关闭广告
     *
     * @param id
     * @return
     */
    @Override
    public String updateByOpen(int id) {
        return adMapping.updateByOpen(id)>0?Reminder.success.getName():Reminder.openerror.getName();
    }
}
